package com.imooc.pan.storage.engine.local;

import com.imooc.pan.core.utils.FileUtil;
import com.imooc.pan.storage.engine.core.AbstractStorageEngine;
import com.imooc.pan.storage.engine.core.context.*;
import com.imooc.pan.storage.engine.local.config.LocalStorageEngineConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

/**
 * 文件存储引擎实现类
 * @author hhb
 * @data 2024/6/10 16:48
 */
@Component
public class LocalStorageEngine extends AbstractStorageEngine {

    @Autowired
    private LocalStorageEngineConfig config;

    /**
     * 存储文件
     * @param context
     * @throws IOException
     */
    @Override
    protected void doStoreFile(StoreFileContext context) throws IOException {
        String basePath = config.getRootFilePath();
        String realFilePath = FileUtil.generateStoreFileRealPath(basePath,context.getFilename());
        FileUtil.writeStreamToFile(context.getInputStream(),new File(realFilePath),context.getTotalSize());
        context.setRealPath(realFilePath);
    }

    @Override
    protected void doDeleteFile(DeleteFileContext context) throws IOException {
        FileUtil.deleteFile(context.getRealPathList());
    }

    /**
     * 存储分片文件
     * @param context
     * @throws IOException
     */
    @Override
    protected void doSaveChunkFile(StoreChunkFileContext context) throws IOException {
        String basePath = config.getRootFileChunkPath();
        String realFileChunkPath = FileUtil.generateStoreFileChunkRealPath(basePath,context.getIdentifier(),context.getChunkNumber());
        FileUtil.writeStreamToFile(context.getInputStream(),new File(realFileChunkPath),context.getTotalSize());
        context.setRealPath(realFileChunkPath);
    }

    @Override
    protected void doMergeFile(MergeFileContext context) throws IOException {
        String basePath = config.getRootFilePath();
        String realFilePath = FileUtil.generateStoreFileRealPath(basePath,context.getFilename());
        FileUtil.createFile(new File(realFilePath));
        //FileUtil.writeStreamToFile(context.getInputStream(),new File(realFilePath),context.getTotalSize());
        List<String> chunkPaths = context.getRealPathList();
        for (String chunkPath : chunkPaths) {
            FileUtil.appendWrite(Paths.get(realFilePath),new File(chunkPath).toPath());
        }
        //删除
        FileUtil.deleteFile(chunkPaths);
        context.setRealPath(realFilePath);
    }

    @Override
    protected void doReadFile(ReadFileContext context) throws IOException {
        File file = new File(context.getRealPath());
        FileUtil.writeFileToOutputStream(new FileInputStream(file),context.getOutputStream(),file.length());
    }
}
